<?php

namespace Es\Struct\Fields;

use Es\Constant\FieldsConst;
use Es\Contract\FieldsInterface;
use Es\Exceptions\CommonExceptions;

/**
 * 索引结构体
 */
class StringStruct implements FieldsInterface
{
    
    private $name;
    private $type;
    private $analyzer;
    private $searchAnalyzer;
    private $keywordIgnoreAbove;

    const TYPE_LIST = [
        FieldsConst::KEYWORD  => 1,
        FieldsConst::TEXT     => 1,
    ];

    /**
     * @throws CommonExceptions
     */
    public function __construct(
        string $name, 
        string $type = FieldsConst::KEYWORD,
        string $analyzer = '',
        string $searchAnalyzer = '',
        int    $keywordIgnoreAbove = 256
    ){
        $this->name               = $name;
        $this->type               = $type;
        $this->analyzer           = $analyzer;
        $this->searchAnalyzer     = $searchAnalyzer;
        $this->keywordIgnoreAbove = $keywordIgnoreAbove;
        if(!isset(self::TYPE_LIST[$type])){
            throw new CommonExceptions(CommonExceptions::FILEDS_NUM_NOT_FOUNT);
        }
    }   
    public function asArray(): array
    {
        if($this->type === FieldsConst::KEYWORD){
            return $this->__initKeyword();
        }else{
            return $this->__initText();
        }
    }
    private function __initKeyword(): array
    {
        return [
            $this->name,
            [
                'type' => $this->type
            ]
        ];
    }
    private function __initText(): array
    {
        $init = [
            'type' => $this->type
        ];
        if(!empty($this->analyzer)){
            $init['analyzer'] = $this->analyzer;
        }
        if(!empty($this->searchAnalyzer)){
            $init['search_analyzer'] = $this->searchAnalyzer;
        }
        $init['fields'] = [
            "keyword" => [
                "type"         => "keyword",
                "ignore_above" => $this->keywordIgnoreAbove
            ]
        ];
        return [$this->name, $init];
    }

}
